<template>
  <view class="content">
    <view class="pop" @click="handle('rule')">活动规则</view>

    <view class="m-box" v-if="data">
      <view class="userInfo">
        <image class="img" :src="data.saasUser.avatar" mode="aspectFill" />
        <view class="name">{{ data.saasUser.name }}</view>
      </view>

      <view class="shareText">“分享给好友，帮您砍价免费拿”</view>

      <view class="goods">
        <image class="img" :src="data.goods_info.cover_pic" mode="aspectFill" />
        <div class="txt">
          <view class="title">{{ data.goods_info.name }}</view>
          <view class="attr">{{ getAttrName(data.attr_list) }}</view>

          <view class="con" v-if="data.data">
            <view class="price">
              <text>￥</text>
              <text>{{ data.data.pay_price | priceBeforeZero }}</text>
              <text>{{ data.data.pay_price | priceAfterZero }}</text>
            </view>

            <view class="num"
              >¥<text>{{ data.data.total_price }}</text></view
            >
          </view>
        </div>
      </view>

      <view class="margin">
        <view class="desc">
          累计已砍<text>￥{{ getCurPrice[0] }}</text
          >，还差<text>￥{{ getCurPrice[1] }}</text></view
        >

        <progressBar :width="getProgressBarValue"></progressBar>

        <view class="progressBarText">
          <view class="price"
            >原价<text>¥ {{ data.data.total_price }}</text>
          </view>
          <view class="timer" v-if="!data.data.used_order_id">
            剩余
            <u-count-down
              bg-color="#f8260a"
              color="#fff"
              :font-size="20"
              :timestamp="getTimestamp"
              @end="handle('endTime')"
            ></u-count-down>
            结束
          </view>
          <view class="price"
            >最低<text>¥{{ data.data.min_price }}</text>
          </view>
        </view>

        <view class="buyBtn" v-if="!data.data.used_order_id">
          <view class="buyBtnItem" v-if="showBuyBtn">
            <view class="btn" @click="handle('buyNow')">直接购买</view>
          </view>

          <view class="buyBtnItem">
            <button open-type="share" v-if="getTimestamp" class="btn btn2">
              分享好友砍一刀
            </button>
            <view v-else class="btn btn2 disabled">分享好友砍一刀</view>
          </view>
        </view>
      </view>
    </view>

    <view class="m-box">
      <view class="rankingList">
        <view class="title">助力排行榜</view>
        <view class="des"
          >共有{{ totalCount }}个好友帮您砍掉¥{{ getCurPrice[0] }}</view
        >

        <view class="list" v-if="items.length">
          <view class="item" v-for="item of items" :key="item.user_id">
            <view class="info">
              <image class="img" :src="item.avatar" mode="aspectFill" />
              <view class="tit">{{ item.name }}</view>
            </view>
            <view class="price">帮砍￥{{ item.cut_price }}</view>
          </view>
        </view>

        <view class="noMore" v-if="moreStatus === 3">没有更多了～</view>
        <view class="noMore" v-else
          >查看更多<i class="iconfont icon-arrow-down"></i
        ></view>
      </view>
    </view>

    <u-popup
      :mask-close-able="false"
      v-model="show"
      mode="center"
      :border-radius="32"
      negative-top="120"
    >
      <view class="popup">
        <image
          class="popupImg"
          :src="asyncImgs.index.cut_price_suc_bg"
          mode="widthFix"
        />

        <view class="popupCon" v-if="data">
          <view class="tit">恭喜您！</view>

          <view class="des"
            >{{ data.is_self_order ? "您一出手就帮自己砍了" : "您帮好友砍了" }}
            <view class="price" v-if="data.log">
              <text>￥</text>
              <text>{{ data.log.cut_price | priceBeforeZero }}</text>
              <text>{{ data.log.cut_price | priceAfterZero }}</text>
            </view></view
          >
          <view class="progressBar">
            <progressBar :width="getProgressBarValue"></progressBar>
          </view>
          <view class="progressBarText">
            <view class="timer">
              剩余
              <u-count-down
                bg-color="#f8260a"
                color="#fff"
                :font-size="20"
                :timestamp="getTimestamp"
              ></u-count-down>
              结束
            </view>
          </view>

          <view class="popupShare">分享给更多好友，可以多砍一刀哦~</view>

          <button
            open-type="share"
            v-if="getTimestamp && getCurPrice[1]"
            class="btn"
          >
            找人帮砍
          </button>
          <view
            v-else-if="!getTimestamp && showBuyBtn"
            class="btn"
            @click="handle('buyNow')"
            >立即购买</view
          >
          <view v-else class="btn disabled">砍价活动结束</view>
        </view>

        <image
          @click="show = false"
          class="popupClose"
          :src="asyncImgs.index.close"
          mode="widthFix"
        />
      </view>
    </u-popup>
  </view>
</template>

<script>
import { cutPriceOrderInfo, cutPriceLogList } from "@/api/marketing/curPrice";
import progressBar from "../components/progressBar";

export default {
  components: {
    progressBar
  },

  data() {
    return {
      data: null,
      show: false,
      id: undefined,

      items: [],
      isEnd: false,
      limit: 10,
      page: 1,
      moreStatus: 1,
      totalCount: 0
    };
  },

  onLoad(opi) {
    if (opi.id) {
      this.id = opi.id;
    }
  },

  onShow() {
    this.clearData();
    this.getData();
  },

  computed: {
    showBuyBtn() {
      let { data } = this;
      if (!data) {
        return false;
      }

      let { buy, pay_price, min_price } = data.data;
      if (
        parseInt(buy) === 0 &&
        parseFloat(pay_price) > parseFloat(min_price)
      ) {
        return false;
      }

      if (new Date().getTime() > data.activity.end_time * 1000) {
        return false;
      }

      if (data.is_self_order !== 1) {
        return false;
      }
      return true;
    },

    getTimestamp() {
      let timestamp = 0,
        { data } = this;
      if (data && data.data && data.data.end_time) {
        let active = new Date().getTime(),
          endTime = data.data.end_time * 1000;

        if (endTime >= active) {
          timestamp = parseInt((endTime - active) / 1000);
        }
      }

      return timestamp;
    },

    getAttrName() {
      return (attr) => {
        if (attr && attr.length) {
          return attr
            .map((el) => el.attr_group_name + ":" + el.attr_name)
            .join();
        }
        return "";
      };
    },

    // arr[0] 已砍 arr[1] 剩余砍价
    getCurPrice() {
      let arr = [0, 0],
        { data } = this;

      if (data) {
        if (data.data.pay_price && data.data.total_price) {
          arr[0] = parseFloat(
            (data.data.total_price - data.data.pay_price).toFixed(2)
          );
        }

        if (data.activity.min_price) {
          arr[1] = parseFloat(
            (
              data.data.total_price -
              data.data.min_price -
              parseFloat(arr[0])
            ).toFixed(2)
          );
        }
      }

      return arr;
    },

    getProgressBarValue() {
      if (!this.data) return;
      let { getCurPrice } = this,
        total_price = parseFloat(this.data.data.total_price),
        min_price = parseFloat(this.data.activity.min_price);

      return (
        parseFloat((getCurPrice[0] / (total_price - min_price)).toFixed(4)) *
        100
      );
    }
  },

  filters: {
    priceBeforeZero(val) {
      if (!val) val = "";
      if (val.indexOf(".") < 0) return `${val}.`;
      return val.substr(0, val.indexOf("."));
    },
    priceAfterZero(val) {
      if (!val) val = "";
      if (val.indexOf(".") < 0) return "00";
      return val.substr(val.indexOf("."), val.length);
    }
  },

  methods: {
    clearData() {
      this.items = [];
      this.isEnd = false;
      this.limit = 10;
      this.page = 1;
      this.moreStatus = 1;
      this.totalCount = 0;
    },

    handle(type) {
      switch (type) {
        case "buyNow":
          this.buyNow();
          break;

        case "endTime":
          this.getData();
          break;

        case "rule":
          uni.navigateTo({
            url: "/marketing/curPrice/rule/index"
          });
          break;
      }
    },

    buyNow() {
      const submit = this.data.data.order_mch_list;

      uni.navigateTo({
        url: `/order/order-submit/order-submit?submit=${submit}&activity_cut_price_order_id=${this.id}`
      });
    },

    async getData() {
      const res = await cutPriceOrderInfo({
        order_id: this.id
      });

      if (!res.code) {
        let {
          is_self_order,
          data,
          activity,
          goods_ext,
          goods_info,
          log,
          logSave,
          saasUser,
          attr_list,
          activity_finished,
          status
        } = res;
        this.data = {
          data,
          activity,
          goods_ext,
          goods_info,
          log,
          logSave,
          saasUser,
          is_self_order,
          activity_finished,
          attr_list: attr_list || [],
          status
        };
        this.getList();
        if (!logSave.code) {
          this.show = true;
        }

        if (activity_finished) {
          this.$utils.hideShareMenu();
        }
      }
    },

    async getList() {
      let { limit, page } = this;
      let res = await cutPriceLogList(
        {
          limit,
          page,
          order_id: this.id
        },
        true
      );
      this.moreStatus = 1;
      uni.stopPullDownRefresh();
      if (!res.code) {
        let { items: oldList } = this,
          { count: totalCount, data: list } = res;

        this.totalCount = totalCount;

        if (list.length) {
          oldList.push(...list);
          this.page = this.page + 1;
        }

        if (oldList.length >= parseInt(totalCount)) {
          this.isEnd = true;
          this.moreStatus = 3;
        }
      }
    }
  },

  onShareAppMessage() {
    let { name: title, cover_pic: imageUrl } = this.data.goods_info;
    return {
      title: "快来帮我砍" + title,
      path: `/marketing/curPrice/active/index?id=${this.id}`,
      imageUrl
    };
  }
};
</script>

<style lang="less" scoped>
.content {
  position: relative;
  padding: 100rpx 20rpx calc(env(safe-area-inset-bottom) + 10rpx);
  background: linear-gradient(90deg, #ff283d 0%, #ff4411 100%);
  min-height: 100vh;

  &:after {
    content: "";
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: calc(env(safe-area-inset-bottom) + 10rpx);
    background: #fff;
  }
}

.m-box {
  margin-bottom: 24rpx;
  padding: 22rpx;
  background: #fff;
  border-radius: 20rpx;
}

.pop {
  position: fixed;
  right: 0;
  top: 20rpx;
  z-index: 10;
  text-align: center;
  width: 138rpx;
  height: 60rpx;
  font-weight: bold;
  color: #f0250e;
  line-height: 60rpx;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 32px 0px 0px 32px;
}

.userInfo {
  text-align: center;
  .img {
    margin-top: -88rpx;
    width: 116rpx;
    height: 116rpx;
    background: #ffffff;
    border-radius: 32px;
    border: 4px solid #ffffff;
  }

  .name {
    padding-top: 6rpx;
    text-align: center;
    font-size: 24rpx;
    color: #8c8c8c;
  }
}

.shareText {
  padding: 26rpx 0 20rpx;
  text-align: center;
  font-size: 36rpx;
  font-weight: bold;
}

.goods {
  display: flex;
  padding: 24rpx;
  background: #fff4e8;
  border-radius: 20rpx;

  .img {
    margin-right: 24rpx;
    width: 166rpx;
    height: 166rpx;
    background: #fff;
    border-radius: 10rpx;
  }

  .txt {
    flex: 1;
    overflow: hidden;

    .con {
      display: flex;
      align-items: flex-end;
      padding-top: 18rpx;
      font-size: 24rpx;
    }

    .num {
      margin-left: 10rpx;
      color: #8c8c8c;

      text {
        position: relative;
        color: #8c8c8c;

        &:after {
          content: "";
          position: absolute;
          left: 0;
          top: 50%;
          width: 100%;
          height: 1px;
          background: #8c8c8c;
        }
      }
    }
  }

  .title {
    display: -webkit-box;
    white-space: normal;
    text-overflow: ellipsis;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    word-break: break-all;
    overflow: hidden;
    font-size: 28rpx;
    font-weight: bold;
    color: #262626;
    line-height: 40rpx;
    max-height: 80rpx;
  }

  .price {
    display: flex;
    align-items: flex-end;
    font-size: 24rpx;
    font-weight: bold;
    color: #f0250e;

    text:nth-child(2) {
      font-size: 32rpx;
    }
  }
}

.desc {
  padding: 48rpx 0 40rpx;
  text-align: center;
  font-size: 30rpx;
  color: #262626;

  text {
    color: #f0250e;
  }
}

.progressBarText {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 0 30rpx;

  .price {
    color: #8c8c8c;

    text {
      color: #f8260a;
    }
  }

  .timer {
    display: flex;
    align-items: center;

    ::v-deep {
      .u-countdown {
        margin: 0 10rpx;
      }
    }
  }
}

.margin {
  margin: 0 14rpx;
}

.buyBtn {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 -13rpx;

  .buyBtnItem {
    flex: 1;
    overflow: hidden;
    padding: 0 13rpx;
  }

  .btn {
    padding: 0;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    color: #fff;
    border-radius: 32px;
    font-size: 32rpx;
    background: linear-gradient(90deg, #faa60f 0%, #fbbc10 100%);
  }

  .btn2 {
    background: linear-gradient(90deg, #f22407 0%, #f84d17 100%);
  }

  .disabled {
    background: #8c8c8c;
  }
}

.rankingList {
  .title {
    font-size: 36rpx;
    text-align: center;
  }

  .des {
    padding: 10rpx 0 26rpx;
    font-size: 22rpx;
    color: #ff7333;
    text-align: center;
  }

  .list {
    overflow: hidden;
  }

  .item {
    display: flex;
    align-items: center;
    margin-bottom: 16rpx;
    padding: 16rpx 32rpx 16rpx 20rpx;
    background: #f2f2f2;
    border-radius: 10rpx;
  }

  .info {
    flex: 1;
    display: flex;
    align-items: center;
    overflow: hidden;

    .img {
      margin-right: 16rpx;
      width: 50rpx;
      height: 50rpx;
      border-radius: 32px;
      background: #fff;
    }

    .tit {
      flex: 1;
      overflow: hidden;
    }
  }

  .price {
    color: #f8260a;
  }
}

.noMore {
  margin-top: 26rpx;
  padding: 24rpx 0 0;
  border-top: 1px solid #f2f2f2;
  text-align: center;
  color: #8c8c8c;
}

.popup {
  position: relative;
  width: 84vw;
}

.popupImg {
  display: block;
  width: 100%;
}

.popupCon {
  position: absolute;
  left: 30rpx;
  right: 30rpx;
  bottom: 172rpx;
  padding: 32rpx;
  background: #fff;
  border-radius: 20rpx;
  overflow: hidden;
  text-align: center;
  box-sizing: border-box;

  .tit {
    padding-bottom: 10rpx;
    font-size: 40rpx;
  }

  .des {
    font-size: 30rpx;
    display: flex;
    justify-content: center;
    align-items: flex-end;
  }

  .progressBarText {
    justify-content: center;
  }

  .price {
    display: flex;
    align-items: flex-end;
    color: #f0250e;

    text:nth-child(2) {
      font-size: 40rpx;
      line-height: 1.2;
    }
  }

  .btn {
    margin: 36rpx auto 0;
    width: 302rpx;
    height: 80rpx;
    line-height: 80rpx;
    background: linear-gradient(90deg, #f22407 0%, #f84d17 100%);
    border-radius: 32px;
    font-size: 32rpx;
    color: #fff;

    &.disabled {
      background: #8c8c8c;
    }
  }
}

.progressBar {
  margin: 38rpx 16rpx 0;
}

.popupShare {
  padding-top: 24rpx;
  border-top: 1px dashed #ededed;
  font-size: 24rpx;
  color: #f1302f;
}

::v-deep {
  .u-mode-center-box {
    background: none !important;
  }
}

.popup {
  padding-bottom: 140rpx;
}
.popupClose {
  position: absolute;
  bottom: 0;
  left: 50%;
  margin-left: -40rpx;
  width: 80rpx;
}
</style>
